import { logger } from '$common';
import { agentConfig } from '../config';
import { AgentState } from './state';
import { io, Socket } from 'socket.io-client';
import { RegisteringState } from './registeringState';
export class ConnectingState extends AgentState {

  constructor() {
    super('connecting');
  }

  async registerAbilities() { this.warnJump(); }
  async onSimulationRequest() { this.warnJump(); }

  async establishConnection() {

    const { gatewayHost, gatewayPort, identity, advertiseIp } = agentConfig;
    logger.info(`🚀 =>> initializing long connection to gateway ${gatewayHost}:${gatewayPort}...`);

    const connection: Socket = io(`http://${gatewayHost}:${gatewayPort}/sim`, {
      transports: ['websocket'],
      query: { identity, advertiseIp }
    });

    connection.on('connect', async () => {
      logger.info(`🚀 ==> connected to ${gatewayHost}:${gatewayPort}`);
      this.context.saveSocketConnection(connection);
      this.context.transitionTo(RegisteringState.Instance);
      await this.context.registerAbilities();
    });
    connection.on('disconnect', (reason) => {
      logger.warn(`❌ connection was disconnected : ${reason}`);
    });

    connection.on('connect_error', (error) => {
      logger.error(`😫 connection error : ${error.message}`);
    });

    connection.io.on('reconnect_attempt', (attempt) => {
      logger.info(`💪 connecting retry ${attempt} `);
    });

    connection.io.on('reconnect', (reconnectionTimes: number) => {
      logger.info(`🌈 Reconnected to gateway, The number of retries is ${reconnectionTimes}`);
    });
  }
}